const path = require('path')
const EsLintWebpackPlugin = require('eslint-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

// 相对路径转绝对路径
const resolvePath = _path => path.resolve(__dirname, _path)

// 获取 cross-env 环境变量
const isEnvProduction = process.env.NODE_ENV === 'production'

const getStyleLoaders = (prevLoader) => {
  return [
    // 生产环境将css单独抽取成文件，开发环境直接只用 style-loader
    isEnvProduction ? MiniCssExtractPlugin.loader : 'style-loader',
    // 开发环境缓存css文件
    !isEnvProduction && 'cache-loader',
    'css-loader',
    {
      // 处理css兼容问题
      loader: 'postcss-loader',
      options: {
        postcssOptions: {
          plugins: ['postcss-preset-env']
        }
      }
    },
    prevLoader
  ].filter(Boolean)
}

module.exports = {

  mode: isEnvProduction ? 'production' : 'development',
  devtool: isEnvProduction ? false : 'eval-cheap-module-source-map',

  entry: resolvePath('../src/index.tsx'),

  module: {
    rules: [{
      oneOf: [{
        test: /\.css$/,
        use: getStyleLoaders()
      }, {
        test: /\.less$/,
        use: getStyleLoaders('less-loader')
      }, {
        test: /\.s[ac]ss$/,
        use: getStyleLoaders('sass-loader')
      }, {
        // 处理图片
        test: /\.(jpe?g|png|gif|webp|svg)$/,
        type: 'asset',
        generator: {
          filename: 'assets/img/[hash:10][ext]'
        },
        parser: {
          dataUrlCondition: {
            // 小于60kb的图片会被base64处理
            maxSize: 60 * 1024
          }
        }
      }, {
        // 处理字体资源
        test: /\.(woff2?|ttf)$/,
        type: 'asset/resource'
      }, {
        test: /\.(js|jsx|ts|tsx)$/,
        // 只处理 src 下的文件，排除其他如 node_modules 的处理
        include: [resolvePath('../src'), resolvePath('../library')],
        loader: 'babel-loader',
        options: {
          // 开启 babel 缓存
          cacheDirectory: true,
          // 关闭缓存压缩
          cacheCompression: false,
          // 开发环境激活TSX的HMR
          plugins: [
            !isEnvProduction && 'react-refresh/babel'
          ].filter(Boolean)
        }
      }]
    }]
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: resolvePath('../public/index.html')
    }),
    new EsLintWebpackPlugin({
      context: resolvePath('../'),
      files: ['src', 'library'],
      cache: true,
      cacheLocation: resolvePath('../node_modules/.cache/.eslintCache')
    }),
  ],

  resolve: {
    alias: {
      '@': resolvePath('../src'),
      '@library': resolvePath('../library'),
    },
    extensions: ['.js', '.ts', '.jsx', '.tsx'],
  },

  // 关闭性能分析，提升打包速度
  performance: false
}
